package no.mehdi.usereg.web.form;

import java.io.Serializable;
import java.util.Date;
import java.util.EventListener;
import java.util.EventObject;

import no.mehdi.usereg.rfid.controllers.RFIDController;
import no.mehdi.usereg.rfid.exceptions.RFIDException;

import org.ajax4jsf.event.PushEventListener;

public class RfidPush implements Runnable, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String uuid = "";

	private boolean enabled = false;

	private Date startDate;

	PushEventListener listener;

	private Thread thread;

	private RFIDController rfid;

	public void addListener(EventListener listener) {
		synchronized (listener) {
			if (this.listener != listener) {
				this.listener = (PushEventListener) listener;
			}
		}
	}
	public void fireListener(){
		listener.onEvent(new EventObject(this));
	}
	@Override
	public void run() {
		try {
			getRfid().startRfid();
			getRfid().setAntennaOn();
			getRfid().setLedOn();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getUuid() {
		return uuid;
	}

	public void start() {
		if (thread == null) {
			thread = new Thread(this);
			thread.setDaemon(true);
			thread.start();
			setStartDate(new Date());
			setEnabled(true);
		}
	}

	public void stop() {
		if (thread != null) {

			try {

				getRfid().setAntennaOff();
				getRfid().setLedOff();
				getRfid().stopRfid();
				
			} catch (RFIDException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				thread = null;
				System.gc();
			}
		}
		setEnabled(false);
	}

	public Thread getThread() {
		return thread;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	public void setRfid(RFIDController rfid) {
		this.rfid = rfid;
	}
	public RFIDController getRfid() {
		return rfid;
	}
	

}
